<?php
/**
 * Created by PhpStorm.
 * User: wuchunyin
 * Date: 2018/11/8
 * Time: 13:36
 */

namespace app\index\controller;
use app\index\base_controller\BaseController;
use app\index\table\FacilityAlterTable;
use app\index\table\FacilityTable;
use think\Db;
use think\Exception;

class Facility extends BaseController{

    /**
     * page--基本信息
     */
    public function facilityList(){
        return view('facility_list');
    }

    /**
     * action--获取信息
     */
    public function getFacilityList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";

        if(empty($sort)){
            $sortStr = 'FACILITY_NO desc';
        }

        $condition = null;

        $listCondition = Login::getListConditionSb();
        if (!empty($listCondition['FACILITY_NO'])) {
            $value = $listCondition['FACILITY_NO'];
            $condition[] = ['FACILITY_NO','like',"$value%"];
        }
        if (!empty($listCondition['FACILITY'])) {
            $value = $listCondition['FACILITY'];
            $condition[] = ['FACILITY','like',"%$value%"];
        }
        if (!empty($listCondition['FACITYPE_ID'])) {
            $value = $listCondition['FACITYPE_ID'];
            $condition[] = ['FACITYPE_ID','=',$value];
        }
        if (!empty($listCondition['DEPART_BELONG'])) {
            $value = $listCondition['DEPART_BELONG'];
            $condition[] = ['DEPART_BELONG','=',$value];
        }
        if (!empty($listCondition['DEPART_USE'])) {
            $value = $listCondition['DEPART_USE'];
            $condition[] = ['DEPART_USE','=',$value];
        }
        if (!empty($listCondition['BELONG_ID'] || $listCondition['BELONG_ID']==='000')) {
            $value = $listCondition['BELONG_ID'];
            $condition[] = ['BELONG_ID','=',$value];
        }
        if (!empty($listCondition['COUNTRY_ID'])) {
            $value = $listCondition['COUNTRY_ID'];
            $condition[] = ['COUNTRY_ID','=',$value];
        }
        if (!empty($listCondition['STATE_ID'])) {
            $value = $listCondition['STATE_ID'];
            $condition[] = ['STATE_ID','=',$value];
        }
        if (!empty($listCondition['PRICE_START'])) {
            $value = $listCondition['PRICE_START'];
            $condition[] = ['PRICE','>=',$value];
        }
        if (!empty($listCondition['PRICE_END'])) {
            $value = $listCondition['PRICE_END'];
            $condition[] = ['PRICE','<=',$value];
        }

        if (!empty($listCondition['ENTERTIME_START'])) {
            $value = Db::raw("to_date('{$listCondition['ENTERTIME_START']}','yyyy-mm-dd')");
            $condition[] = ['ENTERTIME','>=',$value];
        }
        if (!empty($listCondition['ENTERTIME_END'])) {
            $value = Db::raw("to_date('{$listCondition['ENTERTIME_END']}','yyyy-mm-dd')");
            $condition[] = ['ENTERTIME','<=',$value];
        }


        try{
            $listSql = FacilityTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->fetchSql()->select();
            $list = Db::query($listSql);
            $totalSql = FacilityTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page--新增
     */
    public function addPage(){
        $config = FacilityTable::getConfigAdd();
        $data = null;
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('facility_add');
    }

    /**
     * action 新增
     */
    public function add() {
        $data = input();
        try{
            FacilityTable::add($data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--编辑
     */
    public function editPage(){
        $facilityNo = input('facilityNo');
        $config = FacilityTable::getConfigEdit();
        $data = FacilityTable::get($facilityNo);
//        dump($data);
//        return;
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('facility_edit');
    }

    /**
     * 编辑
     */
    public function edit() {
        $facilityNo = input('FACILITY_NO');
        $data = input();
        try{
            FacilityTable::update(['FACILITY_NO'=>$facilityNo],$data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--高级查询
     */
    public function searchPage(){
        $this->view->engine->layout('layout_popup');
        return view('facility_search');
    }

    /*
     * page 导出Excel
     */
    public function exportExcel(){
        $sortStr = 'FACILITY_NO desc';
        $start = input('start');
        $startL = $start-1;
        $end = input('end');
        $endL = $end-$start+1;

        $condition = null;
        $listCondition = Login::getListConditionSb();
        if (!empty($listCondition['FACILITY_NO'])) {
            $value = $listCondition['FACILITY_NO'];
            $condition[] = ['FACILITY_NO','like',"$value%"];
        }
        if (!empty($listCondition['FACILITY'])) {
            $value = $listCondition['FACILITY'];
            $condition[] = ['FACILITY','like',"%$value%"];
        }
        if (!empty($listCondition['FACITYPE_ID'])) {
            $value = $listCondition['FACITYPE_ID'];
            $condition[] = ['FACITYPE_ID','=',$value];
        }
        if (!empty($listCondition['DEPART_BELONG'])) {
            $value = $listCondition['DEPART_BELONG'];
            $condition[] = ['DEPART_BELONG','=',$value];
        }
        if (!empty($listCondition['DEPART_USE'])) {
            $value = $listCondition['DEPART_USE'];
            $condition[] = ['DEPART_USE','=',$value];
        }
        if (!empty($listCondition['BELONG_ID'] || $listCondition['BELONG_ID']==='000')) {
            $value = $listCondition['BELONG_ID'];
            $condition[] = ['BELONG_ID','=',$value];
        }
        if (!empty($listCondition['COUNTRY_ID'])) {
            $value = $listCondition['COUNTRY_ID'];
            $condition[] = ['COUNTRY_ID','=',$value];
        }
        if (!empty($listCondition['STATE_ID'])) {
            $value = $listCondition['STATE_ID'];
            $condition[] = ['STATE_ID','=',$value];
        }
        if (!empty($listCondition['PRICE_START'])) {
            $value = $listCondition['PRICE_START'];
            $condition[] = ['PRICE','>=',$value];
        }
        if (!empty($listCondition['PRICE_END'])) {
            $value = $listCondition['PRICE_END'];
            $condition[] = ['PRICE','<=',$value];
        }

        if (!empty($listCondition['ENTERTIME_START'])) {
            $value = Db::raw("to_date('{$listCondition['ENTERTIME_START']}','yyyy-mm-dd')");
            $condition[] = ['ENTERTIME','>=',$value];
        }
        if (!empty($listCondition['ENTERTIME_END'])) {
            $value = Db::raw("to_date('{$listCondition['ENTERTIME_END']}','yyyy-mm-dd')");
            $condition[] = ['ENTERTIME','<=',$value];
        }

        try{
            $listSql = FacilityTable::table()->where($condition)->limit($startL,$endL)->order($sortStr)->fetchSql()->select();

            $list = Db::query($listSql);

            FacilityTable::exportExcel($list,"设备$start-$end");
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page--变动信息
     */
    public function facilityAlterList(){
        return view('facility_alter_list');
    }

    /**
     * action--获取变动信息
     */
    public function getFacilityAlterList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'ALTER_DATE desc';
        }

        $condition = null;
        $listCondition = Login::getListConditionSbAlter();
        if (!empty($listCondition['FACILITY_NO'])) {
            $value = $listCondition['FACILITY_NO'];
            $condition[] = ['FACILITY_NO','like',"$value%"];
        }
        if (!empty($listCondition['RECEIPT_NO'])) {
            $value = $listCondition['RECEIPT_NO'];
            $condition[] = ['RECEIPT_NO','like',"$value%"];
        }
        if (!empty($listCondition['ALTERCAUSE_ID'])) {
            $value = $listCondition['ALTERCAUSE_ID'];
            $condition[] = ['ALTERCAUSE_ID','=',$value];
        }
        if (!empty($listCondition['BELONG_ID']) || $listCondition['BELONG_ID']==='000') {
            $value = $listCondition['BELONG_ID'];
            $condition[] = ['BELONG_ID','=',$value];
        }
        if (!empty($listCondition['IS_AUDIT'] || $listCondition['IS_AUDIT']==='0')) {
            $value = $listCondition['IS_AUDIT'];
            $condition[] = ['IS_AUDIT','=',$value];
        }
        if (!empty($listCondition['ALTER_DATE_START'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_DATE_START']}','yyyy-mm-dd')");
            $condition[] = ['ALTER_DATE','>=',$value];
        }
        if (!empty($listCondition['ALTER_DATE_END'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_DATE_END']}','yyyy-mm-dd')");
            $condition[] = ['ALTER_DATE','<=',$value];
        }


        try{
            $listSql = FacilityAlterTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->fetchSql()->select();
            $list = Db::query($listSql);
            $totalSql = FacilityAlterTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page--变动高级查询
     */
    public function alterSearchPage(){
        $this->view->engine->layout('layout_popup');
        return view('facility_alter_search');
    }

    /**
     * page--新增变动
     */
    public function alterAddPage(){
        $idList = input('idList');
        $list = FacilityTable::table()->where([['FACILITY_NO','in',$idList]])->select();
        if(empty($list)){
            return '查询设备信息失败';
        }
        $this->assign('ids',$idList);
        $this->assign('list',$list);
        $this->view->engine->layout('layout_popup');
        return view('facility_alter_add');
    }

    /**
     * action 新增变动
     */
    public function addAlter(){
        $ids = input('ids');
        $alterType = input('ALTERTYPE_ID');
        $alterTime = input('ALTER_DATE');
        if(!in_array($alterType,['02','05','99'])){
            return json_encode(['code'=>'0','msg'=>'错误的变动类型']);
        }
        if(empty($alterTime)){
            return json_encode(['code'=>'0','msg'=>'请输入变动时间']);
        }

        try{
            Db::startTrans();
            $idArr = explode(',',$ids);
            $receiptNo = FacilityAlterTable::getReceiptNo();

//            $disposeNo = FacilityAlterTable::getDisposeNo();
            foreach ($idArr as $id){

                $facility = FacilityTable::get($id);
                if(empty($facility)){
                    Db::rollback();
                    return json_encode(['code'=>'0','msg'=>"查询设备信息[$id]失败"]);
                }

                if($alterType == '02'){
                    //记录变动信息
                    FacilityAlterTable::add([
                        'FACILITY_NO'=>$id
                        ,'ALTERTYPE_ID'=>'02'
                        ,'RECEIPT_NO'=>$receiptNo
                        ,'ALTER_DATE'=>$alterTime
                        ,'ALTERCAUSE_ID'=>input('ALTERCAUSE_ID')
                        ,'PRICE_BEF'=>$facility['PRICE']
                        ,'PRICE_AFT'=>input('PRICE_AFT')
                        ,'COMMENTS'=>input('COMMENTS')
                        ,'IS_AUDIT'=>input('IS_AUDIT')
                        ,'BELONG_ID'=>$facility['BELONG_ID']
                    ]);
                    //更新设备信息
                    $price = $facility['PRICE'] + input('PRICE_AFT');
                    FacilityTable::update(['FACILITY_NO'=>$id],['PRICE'=>$price]);
                }

                if($alterType == '05'){
                    $departIdBef = $facility['DEPART_USE'];
                    $departBefore = Db::table('DICT_SB_DEPARTMENT')->where(['DEPART_ID'=>$departIdBef])->find();
                    $departIdAft = input('DEPARTID_AFT');
                    $departAfter = Db::table('DICT_SB_DEPARTMENT')->where(['DEPART_ID'=>$departIdAft])->find();
                    if(empty($departAfter)){
                        Db::rollback();
                        return json_encode(['code'=>'0','msg'=>"查询调入部门信息失败"]);
                    }

                    //记录变动信息
                    FacilityAlterTable::add([
                        'FACILITY_NO'=>$id
                        ,'ALTERTYPE_ID'=>'05'
                        ,'RECEIPT_NO'=>$receiptNo
                        ,'ALTER_DATE'=>$alterTime
                        ,'ALTERCAUSE_ID'=>input('ALTERCAUSE_ID')
                        ,'DEPARTID_BEF'=>$departIdBef
                        ,'DEPARTNAME_BEF'=>empty($departBefore)?'':$departBefore['DEPART_SHORT']
                        ,'DEPARTID_AFT'=>$departIdAft
                        ,'DEPARTNAME_AFT'=>$departAfter['DEPART_SHORT']
                        ,'COMMENTS'=>input('COMMENTS')
                        ,'IS_AUDIT'=>input('IS_AUDIT')
                        ,'BELONG_ID'=>$facility['BELONG_ID']
                    ]);
                    //更新设备信息
                    FacilityTable::update(['FACILITY_NO'=>$id],['DEPART_USE'=>$departIdAft]);
                }

                if($alterType == '99'){
                    //记录变动信息
                    FacilityAlterTable::add([
                        'FACILITY_NO'=>$id
                        ,'ALTERTYPE_ID'=>'99'
                        ,'RECEIPT_NO'=>$receiptNo
                        ,'ALTER_DATE'=>$alterTime
                        ,'ALTERCAUSE_ID'=>input('ALTERCAUSE_ID')
                        ,'DISPOSE'=>input('DISPOSE')
                        ,'DISPOSE_RECNO'=>input('DISPOSE_RECNO')
                        ,'DISPOSE_PRICE'=>input('DISPOSE_PRICE')
                        ,'COMMENTS'=>input('COMMENTS')
                        ,'IS_AUDIT'=>input('IS_AUDIT')
                        ,'BELONG_ID'=>$facility['BELONG_ID']
                    ]);
                    //更新设备信息
                    FacilityTable::update(['FACILITY_NO'=>$id],['STATE_ID'=>'99']);
                }
            }

            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page 查看变动
     */
    public function alterDetailPage(){
        $receiptNo = input('receiptNo');
        $alterList = FacilityAlterTable::table()->where(['RECEIPT_NO'=>$receiptNo])->select();
        $this->assign('alterList',$alterList);
        $this->view->engine->layout('layout_popup');
        return view('facility_alter_detail');
    }

    public function addSession() {
        $condition = input();
        Login::setListConditionSb($condition);
        return json_encode(['code'=>'200']);
    }

    public function addSessionAlter() {
        $condition = input();
        Login::setListConditionSbAlter($condition);
        return json_encode(['code'=>'200']);
    }

    public function importPage() {
        $this->view->engine->layout('layout_popup');
        return view('import');
    }

    public function import() {
        $inputData = input('data');
        $postData = base64_decode($inputData);
        $list = json_decode($postData,true);
        $start = input('start');

        Db::startTrans();
        $fieldList = FacilityTable::FACILITY_FIELD_LIST;
        $fieldCount = count($fieldList);
        foreach ($list as $key => $row) {
            $data = [];

            // 字段赋值
            $i = 0;
            foreach ($row as $key1=>$value) {
                $data[$fieldList[$i]] = $value;
                $i++;
                if ($i>=$fieldCount) {
                    break;
                }
            }

            try{
                FacilityTable::addImport($data);
            }
            catch (Exception $e){
                Db::rollback();
                return json_encode(['code'=>'0','msg'=>"第".($key + $start)."行数据写入出错",'data'=>$e->getMessage()]);
            }
        }

        Db::commit();
        return json_encode(['code'=>'200','msg'=>'导入成功']);
    }

    public function exportExcelPage() {
        $condition = null;

        $listCondition = Login::getListConditionSb();
        if (!empty($listCondition['FACILITY_NO'])) {
            $value = $listCondition['FACILITY_NO'];
            $condition[] = ['FACILITY_NO','like',"$value%"];
        }
        if (!empty($listCondition['FACILITY'])) {
            $value = $listCondition['FACILITY'];
            $condition[] = ['FACILITY','like',"%$value%"];
        }
        if (!empty($listCondition['FACITYPE_ID'])) {
            $value = $listCondition['FACITYPE_ID'];
            $condition[] = ['FACITYPE_ID','=',$value];
        }
        if (!empty($listCondition['DEPART_BELONG'])) {
            $value = $listCondition['DEPART_BELONG'];
            $condition[] = ['DEPART_BELONG','=',$value];
        }
        if (!empty($listCondition['DEPART_USE'])) {
            $value = $listCondition['DEPART_USE'];
            $condition[] = ['DEPART_USE','=',$value];
        }
        if (!empty($listCondition['BELONG_ID'] || $listCondition['BELONG_ID']==='000')) {
            $value = $listCondition['BELONG_ID'];
            $condition[] = ['BELONG_ID','=',$value];
        }
        if (!empty($listCondition['COUNTRY_ID'])) {
            $value = $listCondition['COUNTRY_ID'];
            $condition[] = ['COUNTRY_ID','=',$value];
        }
        if (!empty($listCondition['STATE_ID'])) {
            $value = $listCondition['STATE_ID'];
            $condition[] = ['STATE_ID','=',$value];
        }
        if (!empty($listCondition['PRICE_START'])) {
            $value = $listCondition['PRICE_START'];
            $condition[] = ['PRICE','>=',$value];
        }
        if (!empty($listCondition['PRICE_END'])) {
            $value = $listCondition['PRICE_END'];
            $condition[] = ['PRICE','<=',$value];
        }

        if (!empty($listCondition['ENTERTIME_START'])) {
            $value = Db::raw("to_date('{$listCondition['ENTERTIME_START']}','yyyy-mm-dd')");
            $condition[] = ['ENTERTIME','>=',$value];
        }
        if (!empty($listCondition['ENTERTIME_END'])) {
            $value = Db::raw("to_date('{$listCondition['ENTERTIME_END']}','yyyy-mm-dd')");
            $condition[] = ['ENTERTIME','<=',$value];
        }


        try{
            $totalSql = FacilityTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            $total = $total[0]['TP_COUNT'];
            $this->assign('total',$total);

            $everyCount = 2000;
            $arr = [];
            if ($total<=$everyCount) {
              $arr[] = ['start'=>1,'end'=>$total];
            } else {
                $fullTotal =  floor($total/$everyCount);
                $left =  $total%$everyCount;
                for ($i = 1; $i<=$fullTotal; $i++) {
                    $start = ($i-1)*$everyCount +1;
                    $end = $start+$everyCount-1;
                    $arr[] = ['start'=>$start,'end'=>$end];
                }
                if ($left>0) {
                    $start = $fullTotal*$everyCount+1;
                    $end =  $start+$left-1;
                    $arr[] = ['start'=>$start,'end'=>$end];
                }
            }
            $this->assign('downList',$arr);

            $this->view->engine->layout('layout_popup');
            return view('export_excel');
        }
        catch (Exception $e){
            return $e->getMessage();
        }

    }

}